package com.water.quality.testing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.math.MathUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.water.quality.testing.common.CustomException;
import com.water.quality.testing.dao.User;
import com.water.quality.testing.dto.req.UserLoginReqDTO;
import com.water.quality.testing.dto.req.UserModifyReqDTO;
import com.water.quality.testing.dto.req.UserRegisterReqDTO;
import com.water.quality.testing.dto.resp.UserLoginRespDTO;
import com.water.quality.testing.mapper.UserMapper;
import com.water.quality.testing.service.UserService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author LYT0905
 * @Description:
 * @Date: 2024/06/21 17:40:50
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam, HttpSession session) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, requestParam.getUsername())
                .eq(User::getPassword, DigestUtil.md5Hex(requestParam.getPassword()));
        // 查找用户
        User user = baseMapper.selectOne(queryWrapper);
        // 如果没有找到，就代表用户名或密码错误
        if (ObjectUtils.isNull(user)){
            throw new CustomException("用户名或密码错误，请重试");
        }
        // 将 id 塞进会话中，实现过滤（未登录不能看）
        session.setAttribute("user", user.getId());
        // 返回用户 id
        UserLoginRespDTO userLoginRespDTO = new UserLoginRespDTO();
        userLoginRespDTO.setId(user.getId());
        return userLoginRespDTO;
    }

    /**
     * 用户注册
     * @param requestParam  请求参数
     */
    @Override
    public void register(UserRegisterReqDTO requestParam) {
        // 因为数据库层面对用户名做了唯一索引约束，所以需要 try catch
        try {
            // 插入用户表，进行注册
            User user = BeanUtil.toBean(requestParam, User.class);
            String md5Hex = DigestUtil.md5Hex(requestParam.getPassword());
            user.setPassword(md5Hex);
            baseMapper.insert(user);
        }catch (DuplicateKeyException ex){
            throw new CustomException("用户名已存在，请更换之后再试");
        }
    }

    /**
     * 修改密码
     * @param requestParam  请求参数
     */
    @Override
    public void modify(UserModifyReqDTO requestParam, HttpSession session) {
        LambdaUpdateWrapper<User> updateWrapper = Wrappers.lambdaUpdate(User.class)
                .eq(User::getId, Long.parseLong(requestParam.getId()))
                .set(User::getPassword, DigestUtil.md5Hex(requestParam.getPassword()));
        baseMapper.update(null, updateWrapper);
        session.removeAttribute("user");
    }
}
